package com.pai4j.pgc.service;

import com.pai4j.common.bean.PAIPageResponseBeanUtil;
import com.pai4j.common.enums.*;
import com.pai4j.domain.vo.request.creator.ApplyCreatorRequestVO;
import com.pai4j.domain.vo.request.creator.AuditCreatorRequestVO;
import com.pai4j.domain.vo.request.creator.UpdateCreatorRequestVO;
import com.pai4j.domain.vo.response.creator.*;
import com.pai4j.pgc.dao.ICreatorAuditRecordDAO;
import com.pai4j.pgc.dao.ICreatorDAO;
import com.pai4j.pgc.entity.CreatorAuditRecordEntity;
import com.pai4j.pgc.entity.CreatorEntity;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 创作者服务
 * 提供创作者申请、审核、信息管理、等级管理、收益管理等核心功能
 *
 * @author: CYM-pai
 * @date: 2025/11/01
 */
@Slf4j
@Service
public class CreatorService {
    
    @Resource
    private ICreatorDAO creatorDAO;
    
    @Resource
    private ICreatorAuditRecordDAO creatorAuditRecordDAO;
    
    @Resource
    private CreatorCacheService creatorCacheService;
    
    /**
     * 申请成为创作者
     *
     * @param request 申请请求
     * @return 申请是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean applyCreator(ApplyCreatorRequestVO request) {
        String userId = request.getUserId();
        
        // 1. 检查用户是否已是创作者
        Optional<CreatorEntity> existingCreator = creatorDAO.findByUserIdAndDeleteFlag(userId, 
                DeleteFlagCodeEnum.NOT_DELETE.getCode());
        Assert.isTrue(existingCreator.isEmpty(), "用户已申请过创作者，请勿重复申请！");
        
        // 2. 创建创作者实体
        CreatorEntity creator = new CreatorEntity();
        BeanUtils.copyProperties(request, creator);
        creator.setStatus(CreatorStatusEnum.PENDING.getCode());
        creator.setLevel(CreatorLevelEnum.BEGINNER.getLevel());
        creator.setCreditScore(80); // 初始信用分80
        creator.setExperiencePoints(0);
        creator.setFollowerCount(0);
        creator.setArticleCount(0);
        creator.setTotalViews(0L);
        creator.setTotalLikes(0L);
        creator.setTotalIncome(0L);
        creator.setAvailableBalance(0L);
        creator.setFrozenBalance(0L);
        creator.setDeleteFlag(DeleteFlagCodeEnum.NOT_DELETE.getCode());
        creator.setCreateBy(userId);
        
        // 3. 保存创作者信息
        creator = creatorDAO.save(creator);
        log.info("用户申请成为创作者: userId={}, creatorId={}", userId, creator.getId());
        
        // 4. 触发自动审核
        AutoAuditResult autoAuditResult = autoAudit(creator);
        
        // 5. 创建审核记录
        createAuditRecord(creator, autoAuditResult);
        
        // 6. 如果自动审核通过，更新创作者状态
        if (autoAuditResult.isPassed()) {
            creator.setStatus(CreatorStatusEnum.APPROVED.getCode());
            creator.setAuditTime(new Date());
            creator.setAuditBy("SYSTEM_AUTO");
            creatorDAO.save(creator);
            log.info("创作者自动审核通过: userId={}, score={}", userId, autoAuditResult.getScore());
        }
        
        // 7. 刷新缓存
        refreshCreatorCache(userId);
        
        return true;
    }
    
    /**
     * 自动审核逻辑
     * 规则：
     * - 手机号已验证：30分
     * - 实名认证（真实姓名非空）：40分
     * - 擅长领域填写：20分
     * - 简介完整度：10分
     * - 阈值：≥80分自动通过
     *
     * @param creator 创作者实体
     * @return 审核结果
     */
    private AutoAuditResult autoAudit(CreatorEntity creator) {
        int score = 0;
        StringBuilder auditContent = new StringBuilder();
        
        // 手机号验证（30分）
        if (StringUtils.isNotBlank(creator.getPhone())) {
            score += 30;
            auditContent.append("✓ 手机号已验证(+30分); ");
        } else {
            auditContent.append("✗ 手机号未验证(+0分); ");
        }
        
        // 实名认证（40分）
        if (StringUtils.isNotBlank(creator.getRealName())) {
            score += 40;
            auditContent.append("✓ 已实名认证(+40分); ");
        } else {
            auditContent.append("✗ 未实名认证(+0分); ");
        }
        
        // 擅长领域（20分）
        if (creator.getExpertiseFields() != null && !creator.getExpertiseFields().isEmpty()) {
            score += 20;
            auditContent.append("✓ 已填写擅长领域(+20分); ");
        } else {
            auditContent.append("✗ 未填写擅长领域(+0分); ");
        }
        
        // 简介完整度（10分）
        if (StringUtils.isNotBlank(creator.getBio()) && creator.getBio().length() >= 20) {
            score += 10;
            auditContent.append("✓ 简介完整(+10分); ");
        } else {
            auditContent.append("✗ 简介不完整(+0分); ");
        }
        
        auditContent.append("总分: ").append(score).append("/100");
        
        boolean passed = score >= 80;
        String result = passed ? "自动审核通过" : "需转人工审核（得分不足80分）";
        
        return new AutoAuditResult(passed, score, auditContent + " - " + result);
    }
    
    /**
     * 创建审核记录
     */
    private void createAuditRecord(CreatorEntity creator, AutoAuditResult autoAuditResult) {
        CreatorAuditRecordEntity record = new CreatorAuditRecordEntity();
        record.setCreatorId(creator.getId());
        record.setUserId(creator.getUserId());
        record.setAuditType(CreatorAuditTypeEnum.AUTO.getCode());
        record.setAuditStatus(autoAuditResult.isPassed() ? 2 : 0); // 2-已完成 0-待审核
        record.setAuditResult(autoAuditResult.isPassed() ? 1 : null); // 1-通过 null-待定
        record.setAuditContent(autoAuditResult.getContent());
        record.setAutoAuditScore(autoAuditResult.getScore());
        record.setAuditTime(autoAuditResult.isPassed() ? new Date() : null);
        record.setCreateDate(new Date());
        
        creatorAuditRecordDAO.save(record);
        log.info("创建审核记录: creatorId={}, type=AUTO, result={}", creator.getId(), 
                autoAuditResult.isPassed() ? "通过" : "待审核");
    }
    
    /**
     * 人工审核创作者申请（管理员操作）
     *
     * @param request 审核请求
     * @return 审核是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean manualAudit(AuditCreatorRequestVO request) {
        Long creatorId = request.getCreatorId();
        Integer auditResult = request.getAuditResult(); // 1-通过 2-拒绝
        
        // 1. 查询创作者
        CreatorEntity creator = creatorDAO.findById(creatorId)
                .orElseThrow(() -> new IllegalArgumentException("创作者不存在"));
        
        // 2. 更新创作者状态
        if (auditResult == 1) {
            creator.setStatus(CreatorStatusEnum.APPROVED.getCode());
        } else if (auditResult == 2) {
            creator.setStatus(CreatorStatusEnum.REJECTED.getCode());
            creator.setRejectReason(request.getAuditContent());
        }
        creator.setAuditTime(new Date());
        creator.setAuditBy(request.getAuditBy());
        creator.setUpdateBy(request.getAuditBy());
        
        creatorDAO.save(creator);
        log.info("人工审核创作者: creatorId={}, result={}, auditBy={}", creatorId, 
                auditResult == 1 ? "通过" : "拒绝", request.getAuditBy());
        
        // 3. 创建审核记录
        CreatorAuditRecordEntity record = new CreatorAuditRecordEntity();
        record.setCreatorId(creatorId);
        record.setUserId(creator.getUserId());
        record.setAuditType(CreatorAuditTypeEnum.MANUAL.getCode());
        record.setAuditStatus(2); // 已完成
        record.setAuditResult(auditResult);
        record.setAuditContent(request.getAuditContent());
        record.setAuditBy(request.getAuditBy());
        record.setAuditTime(new Date());
        record.setCreateDate(new Date());
        
        creatorAuditRecordDAO.save(record);
        
        // 4. 刷新缓存
        refreshCreatorCache(creator.getUserId());
        
        return true;
    }
    
    /**
     * 根据用户ID查询创作者信息（带缓存）
     *
     * @param userId 用户ID
     * @return 创作者详情
     */
    public CreatorDetailResponseVO getCreatorByUserId(String userId) {
        if (StringUtils.isBlank(userId)) {
            return null;
        }
        
        // 1. 尝试从缓存获取
        CreatorDetailResponseVO cached = creatorCacheService.getCreatorDetailFromCache(userId);
        if (cached != null) {
            // 如果是空对象标记，返回null
            return cached.getId() == null ? null : cached;
        }
        
        // 2. 缓存未命中，查询数据库
        Optional<CreatorEntity> creatorOpt = creatorDAO.findByUserIdAndDeleteFlag(userId, 
                DeleteFlagCodeEnum.NOT_DELETE.getCode());
        
        if (creatorOpt.isEmpty()) {
            // 缓存空值防止缓存穿透
            creatorCacheService.refreshCreatorDetailCache(userId, null);
            return null;
        }
        
        // 3. 转换为响应VO
        CreatorDetailResponseVO detail = convertToDetailResponseVO(creatorOpt.get());
        
        // 4. 刷新缓存
        creatorCacheService.refreshCreatorDetailCache(userId, detail);
        
        return detail;
    }
    
    /**
     * 更新创作者信息
     *
     * @param request 更新请求
     * @return 更新是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateCreator(UpdateCreatorRequestVO request) {
        String userId = request.getUserId();
        
        // 1. 查询创作者
        CreatorEntity creator = creatorDAO.findByUserIdAndDeleteFlag(userId, 
                        DeleteFlagCodeEnum.NOT_DELETE.getCode())
                .orElseThrow(() -> new IllegalArgumentException("创作者不存在"));
        
        // 2. 更新允许修改的字段
        if (StringUtils.isNotBlank(request.getCreatorName())) {
            creator.setCreatorName(request.getCreatorName());
        }
        if (StringUtils.isNotBlank(request.getAvatar())) {
            creator.setAvatar(request.getAvatar());
        }
        if (request.getBio() != null) {
            creator.setBio(request.getBio());
        }
        if (StringUtils.isNotBlank(request.getEmail())) {
            creator.setEmail(request.getEmail());
        }
        if (request.getExpertiseFields() != null) {
            creator.setExpertiseFields(request.getExpertiseFields());
        }
        creator.setUpdateBy(userId);
        
        creatorDAO.save(creator);
        log.info("更新创作者信息: userId={}", userId);
        
        // 3. 刷新缓存
        refreshCreatorCache(userId);
        
        return true;
    }
    
    /**
     * 增加经验值并自动升级
     *
     * @param userId 用户ID
     * @param points 经验值
     */
    @Transactional(rollbackFor = Exception.class)
    public void addExperience(String userId, Integer points) {
        if (StringUtils.isBlank(userId) || points == null || points <= 0) {
            return;
        }
        
        CreatorEntity creator = creatorDAO.findByUserIdAndDeleteFlag(userId, 
                        DeleteFlagCodeEnum.NOT_DELETE.getCode())
                .orElse(null);
        
        if (creator == null) {
            log.warn("创作者不存在，无法增加经验值: userId={}", userId);
            return;
        }
        
        // 增加经验值
        Integer oldExp = creator.getExperiencePoints();
        Integer newExp = oldExp + points;
        creator.setExperiencePoints(newExp);
        
        // 检查是否升级
        CreatorLevelEnum oldLevel = CreatorLevelEnum.getByLevel(creator.getLevel());
        CreatorLevelEnum newLevel = CreatorLevelEnum.getByExperience(newExp);
        
        if (newLevel != null && !newLevel.equals(oldLevel)) {
            creator.setLevel(newLevel.getLevel());
            log.info("创作者升级: userId={}, oldLevel={}, newLevel={}, exp={}", 
                    userId, oldLevel.getName(), newLevel.getName(), newExp);
        }
        
        creatorDAO.save(creator);
        
        // 刷新缓存
        refreshCreatorCache(userId);
        
        log.debug("增加创作者经验值: userId={}, points={}, totalExp={}", userId, points, newExp);
    }
    
    /**
     * 更新信用分
     *
     * @param userId 用户ID
     * @param scoreDelta 信用分变化值（可以是负数）
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateCreditScore(String userId, Integer scoreDelta) {
        if (StringUtils.isBlank(userId) || scoreDelta == null || scoreDelta == 0) {
            return;
        }
        
        CreatorEntity creator = creatorDAO.findByUserIdAndDeleteFlag(userId, 
                        DeleteFlagCodeEnum.NOT_DELETE.getCode())
                .orElse(null);
        
        if (creator == null) {
            log.warn("创作者不存在，无法更新信用分: userId={}", userId);
            return;
        }
        
        Integer oldScore = creator.getCreditScore();
        Integer newScore = Math.max(0, Math.min(100, oldScore + scoreDelta)); // 限制在0-100
        creator.setCreditScore(newScore);
        
        // 如果信用分 < 60，自动禁用创作者权限
        if (newScore < 60 && creator.getStatus().equals(CreatorStatusEnum.APPROVED.getCode())) {
            creator.setStatus(CreatorStatusEnum.DISABLED.getCode());
            log.warn("创作者因信用分过低被自动禁用: userId={}, creditScore={}", userId, newScore);
        }
        
        creatorDAO.save(creator);
        
        // 刷新缓存
        refreshCreatorCache(userId);
        
        log.info("更新创作者信用分: userId={}, delta={}, oldScore={}, newScore={}", 
                userId, scoreDelta, oldScore, newScore);
    }
    
    /**
     * 文章数+1
     *
     * @param userId 用户ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void increaseArticleCount(String userId) {
        updateCountField(userId, "article", 1);
    }
    
    /**
     * 粉丝数变更
     *
     * @param userId 用户ID
     * @param count 变更数量（可以是负数）
     */
    @Transactional(rollbackFor = Exception.class)
    public void increaseFollowerCount(String userId, Integer count) {
        updateCountField(userId, "follower", count);
    }
    
    /**
     * 总阅读量增加
     *
     * @param userId 用户ID
     * @param count 增加数量
     */
    @Transactional(rollbackFor = Exception.class)
    public void increaseTotalViews(String userId, Long count) {
        if (StringUtils.isBlank(userId) || count == null || count <= 0) {
            return;
        }
        
        CreatorEntity creator = creatorDAO.findByUserIdAndDeleteFlag(userId, 
                        DeleteFlagCodeEnum.NOT_DELETE.getCode())
                .orElse(null);
        
        if (creator != null) {
            creator.setTotalViews(creator.getTotalViews() + count);
            creatorDAO.save(creator);
            refreshCreatorCache(userId);
        }
    }
    
    /**
     * 总点赞数增加
     *
     * @param userId 用户ID
     * @param count 增加数量
     */
    @Transactional(rollbackFor = Exception.class)
    public void increaseTotalLikes(String userId, Long count) {
        if (StringUtils.isBlank(userId) || count == null || count <= 0) {
            return;
        }
        
        CreatorEntity creator = creatorDAO.findByUserIdAndDeleteFlag(userId, 
                        DeleteFlagCodeEnum.NOT_DELETE.getCode())
                .orElse(null);
        
        if (creator != null) {
            creator.setTotalLikes(creator.getTotalLikes() + count);
            creatorDAO.save(creator);
            refreshCreatorCache(userId);
        }
    }
    
    /**
     * 更新计数字段的通用方法
     */
    private void updateCountField(String userId, String fieldType, Integer count) {
        if (StringUtils.isBlank(userId) || count == null || count == 0) {
            return;
        }
        
        CreatorEntity creator = creatorDAO.findByUserIdAndDeleteFlag(userId, 
                        DeleteFlagCodeEnum.NOT_DELETE.getCode())
                .orElse(null);
        
        if (creator == null) {
            log.warn("创作者不存在，无法更新{}计数: userId={}", fieldType, userId);
            return;
        }
        
        switch (fieldType) {
            case "article":
                creator.setArticleCount(Math.max(0, creator.getArticleCount() + count));
                break;
            case "follower":
                creator.setFollowerCount(Math.max(0, creator.getFollowerCount() + count));
                break;
        }
        
        creatorDAO.save(creator);
        refreshCreatorCache(userId);
        
        log.debug("更新创作者{}计数: userId={}, count={}", fieldType, userId, count);
    }
    
    /**
     * 增加收益
     *
     * @param userId 用户ID
     * @param amount 金额（单位：分）
     */
    @Transactional(rollbackFor = Exception.class)
    public void addIncome(String userId, Long amount) {
        if (StringUtils.isBlank(userId) || amount == null || amount <= 0) {
            return;
        }
        
        CreatorEntity creator = creatorDAO.findByUserIdAndDeleteFlag(userId, 
                        DeleteFlagCodeEnum.NOT_DELETE.getCode())
                .orElse(null);
        
        if (creator == null) {
            log.warn("创作者不存在，无法增加收益: userId={}", userId);
            return;
        }
        
        creator.setTotalIncome(creator.getTotalIncome() + amount);
        creator.setFrozenBalance(creator.getFrozenBalance() + amount); // 先冻结（防退款）
        
        creatorDAO.save(creator);
        refreshCreatorCache(userId);
        
        log.info("增加创作者收益: userId={}, amount={}分", userId, amount);
    }
    
    /**
     * 冻结金额转为可提现余额
     *
     * @param userId 用户ID
     * @param amount 金额（单位：分）
     */
    @Transactional(rollbackFor = Exception.class)
    public void unfreezeBalance(String userId, Long amount) {
        if (StringUtils.isBlank(userId) || amount == null || amount <= 0) {
            return;
        }
        
        CreatorEntity creator = creatorDAO.findByUserIdAndDeleteFlag(userId, 
                        DeleteFlagCodeEnum.NOT_DELETE.getCode())
                .orElse(null);
        
        if (creator == null) {
            log.warn("创作者不存在，无法解冻金额: userId={}", userId);
            return;
        }
        
        if (creator.getFrozenBalance() < amount) {
            log.warn("冻结金额不足，无法解冻: userId={}, frozen={}, amount={}", 
                    userId, creator.getFrozenBalance(), amount);
            return;
        }
        
        creator.setFrozenBalance(creator.getFrozenBalance() - amount);
        creator.setAvailableBalance(creator.getAvailableBalance() + amount);
        
        creatorDAO.save(creator);
        refreshCreatorCache(userId);
        
        log.info("解冻创作者金额: userId={}, amount={}分", userId, amount);
    }
    
    /**
     * 根据状态分页查询创作者
     *
     * @param status 状态
     * @param pageNo 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    public PAIPageResponseBeanUtil<List<CreatorBaseResponseVO>> pageCreatorsByStatus(
            Integer status, Integer pageNo, Integer pageSize) {
        
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, Sort.by(Sort.Direction.DESC, "createDate"));
        Page<CreatorEntity> page = creatorDAO.findByStatusAndDeleteFlag(status, 
                DeleteFlagCodeEnum.NOT_DELETE.getCode(), pageable);
        
        List<CreatorBaseResponseVO> list = page.getContent().stream()
                .map(this::convertToBaseResponseVO)
                .collect(Collectors.toList());
        
        return PAIPageResponseBeanUtil.success(list, page.getTotalElements(), pageNo, pageSize);
    }
    
    /**
     * 创作者排行榜（按经验值）
     *
     * @param pageNo 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    public PAIPageResponseBeanUtil<List<CreatorBaseResponseVO>> pageCreatorRanking(
            Integer pageNo, Integer pageSize) {
        
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        Page<CreatorEntity> page = creatorDAO.findByDeleteFlagOrderByExperiencePointsDesc(
                DeleteFlagCodeEnum.NOT_DELETE.getCode(), pageable);
        
        List<CreatorBaseResponseVO> list = page.getContent().stream()
                .map(this::convertToBaseResponseVO)
                .collect(Collectors.toList());
        
        return PAIPageResponseBeanUtil.success(list, page.getTotalElements(), pageNo, pageSize);
    }
    
    /**
     * 禁用创作者
     *
     * @param userId 用户ID
     * @param operator 操作人
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean disableCreator(String userId, String operator) {
        CreatorEntity creator = creatorDAO.findByUserIdAndDeleteFlag(userId, 
                        DeleteFlagCodeEnum.NOT_DELETE.getCode())
                .orElseThrow(() -> new IllegalArgumentException("创作者不存在"));
        
        creator.setStatus(CreatorStatusEnum.DISABLED.getCode());
        creator.setUpdateBy(operator);
        
        creatorDAO.save(creator);
        refreshCreatorCache(userId);
        
        log.info("禁用创作者: userId={}, operator={}", userId, operator);
        return true;
    }
    
    /**
     * 启用创作者
     *
     * @param userId 用户ID
     * @param operator 操作人
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean enableCreator(String userId, String operator) {
        CreatorEntity creator = creatorDAO.findByUserIdAndDeleteFlag(userId, 
                        DeleteFlagCodeEnum.NOT_DELETE.getCode())
                .orElseThrow(() -> new IllegalArgumentException("创作者不存在"));
        
        creator.setStatus(CreatorStatusEnum.APPROVED.getCode());
        creator.setUpdateBy(operator);
        
        creatorDAO.save(creator);
        refreshCreatorCache(userId);
        
        log.info("启用创作者: userId={}, operator={}", userId, operator);
        return true;
    }
    
    /**
     * 获取创作者审核记录
     *
     * @param userId 用户ID
     * @return 审核记录列表
     */
    public List<CreatorAuditRecordResponseVO> getAuditRecords(String userId) {
        List<CreatorAuditRecordEntity> records = creatorAuditRecordDAO.findByUserIdOrderByCreateDateDesc(userId);
        
        return records.stream()
                .map(this::convertToAuditRecordResponseVO)
                .collect(Collectors.toList());
    }
    
    /**
     * 获取创作者统计信息
     *
     * @param userId 用户ID
     * @return 统计信息
     */
    public CreatorStatisticsResponseVO getCreatorStatistics(String userId) {
        if (StringUtils.isBlank(userId)) {
            return null;
        }
        
        // 1. 尝试从缓存获取
        CreatorStatisticsResponseVO cached = creatorCacheService.getCreatorStatisticsFromCache(userId);
        if (cached != null) {
            return cached;
        }
        
        // 2. 从数据库查询
        CreatorEntity creator = creatorDAO.findByUserIdAndDeleteFlag(userId, 
                        DeleteFlagCodeEnum.NOT_DELETE.getCode())
                .orElse(null);
        
        if (creator == null) {
            creatorCacheService.refreshCreatorStatisticsCache(userId, null);
            return null;
        }
        
        // 3. 构建统计VO
        CreatorStatisticsResponseVO statistics = new CreatorStatisticsResponseVO();
        statistics.setUserId(creator.getUserId());
        statistics.setCreatorName(creator.getCreatorName());
        statistics.setLevel(creator.getLevel());
        CreatorLevelEnum levelEnum = CreatorLevelEnum.getByLevel(creator.getLevel());
        statistics.setLevelName(levelEnum != null ? levelEnum.getName() : "");
        statistics.setCreditScore(creator.getCreditScore());
        statistics.setExperiencePoints(creator.getExperiencePoints());
        statistics.setFollowerCount(creator.getFollowerCount());
        statistics.setArticleCount(creator.getArticleCount());
        statistics.setTotalViews(creator.getTotalViews());
        statistics.setTotalLikes(creator.getTotalLikes());
        
        // 计算平均值
        if (creator.getArticleCount() > 0) {
            statistics.setAverageViews(creator.getTotalViews() / creator.getArticleCount());
            statistics.setAverageLikes(creator.getTotalLikes() / creator.getArticleCount());
        } else {
            statistics.setAverageViews(0L);
            statistics.setAverageLikes(0L);
        }
        
        // 4. 刷新缓存
        creatorCacheService.refreshCreatorStatisticsCache(userId, statistics);
        
        return statistics;
    }
    
    /**
     * 刷新创作者相关缓存
     */
    private void refreshCreatorCache(String userId) {
        // 删除详情缓存和统计缓存，下次查询时会重新构建
        creatorCacheService.deleteCreatorDetailCache(userId);
        creatorCacheService.deleteCreatorStatisticsCache(userId);
    }
    
    /**
     * 转换为详细响应VO
     */
    private CreatorDetailResponseVO convertToDetailResponseVO(CreatorEntity entity) {
        CreatorDetailResponseVO vo = new CreatorDetailResponseVO();
        BeanUtils.copyProperties(entity, vo);
        
        // 设置状态描述
        CreatorStatusEnum statusEnum = CreatorStatusEnum.getByCode(entity.getStatus());
        vo.setStatusDesc(statusEnum != null ? statusEnum.getDesc() : "");
        
        // 设置等级名称
        CreatorLevelEnum levelEnum = CreatorLevelEnum.getByLevel(entity.getLevel());
        vo.setLevelName(levelEnum != null ? levelEnum.getName() : "");
        
        // 计算下一等级所需经验
        if (levelEnum != null && !levelEnum.equals(CreatorLevelEnum.MASTER)) {
            vo.setNextLevelExp(levelEnum.getExpMax());
        } else {
            vo.setNextLevelExp(null); // 已是最高等级
        }
        
        // 脱敏处理
        if (StringUtils.isNotBlank(entity.getRealName()) && entity.getRealName().length() > 1) {
            vo.setRealName(entity.getRealName().charAt(0) + "**");
        }
        if (StringUtils.isNotBlank(entity.getPhone()) && entity.getPhone().length() >= 11) {
            vo.setPhone(entity.getPhone().substring(0, 3) + "****" + entity.getPhone().substring(7));
        }
        
        return vo;
    }
    
    /**
     * 转换为基础响应VO
     */
    private CreatorBaseResponseVO convertToBaseResponseVO(CreatorEntity entity) {
        CreatorBaseResponseVO vo = new CreatorBaseResponseVO();
        BeanUtils.copyProperties(entity, vo);
        
        // 设置状态描述
        CreatorStatusEnum statusEnum = CreatorStatusEnum.getByCode(entity.getStatus());
        vo.setStatusDesc(statusEnum != null ? statusEnum.getDesc() : "");
        
        // 设置等级名称
        CreatorLevelEnum levelEnum = CreatorLevelEnum.getByLevel(entity.getLevel());
        vo.setLevelName(levelEnum != null ? levelEnum.getName() : "");
        
        return vo;
    }
    
    /**
     * 转换为审核记录响应VO
     */
    private CreatorAuditRecordResponseVO convertToAuditRecordResponseVO(CreatorAuditRecordEntity entity) {
        CreatorAuditRecordResponseVO vo = new CreatorAuditRecordResponseVO();
        BeanUtils.copyProperties(entity, vo);
        
        // 设置审核类型描述
        CreatorAuditTypeEnum typeEnum = CreatorAuditTypeEnum.getByCode(entity.getAuditType());
        vo.setAuditTypeDesc(typeEnum != null ? typeEnum.getDesc() : "");
        
        // 设置审核状态描述
        String[] statusDescs = {"待审核", "审核中", "已完成"};
        if (entity.getAuditStatus() != null && entity.getAuditStatus() < statusDescs.length) {
            vo.setAuditStatusDesc(statusDescs[entity.getAuditStatus()]);
        }
        
        // 设置审核结果描述
        if (entity.getAuditResult() != null) {
            vo.setAuditResultDesc(entity.getAuditResult() == 1 ? "通过" : "拒绝");
        }
        
        return vo;
    }
    
    /**
     * 自动审核结果内部类
     */
    private static class AutoAuditResult {
        private final boolean passed;
        private final int score;
        private final String content;
        
        public AutoAuditResult(boolean passed, int score, String content) {
            this.passed = passed;
            this.score = score;
            this.content = content;
        }
        
        public boolean isPassed() {
            return passed;
        }
        
        public int getScore() {
            return score;
        }
        
        public String getContent() {
            return content;
        }
    }
}

